package com.lyz.interceptors;

import com.lyz.annotations.Auth;
import com.lyz.controller.UserController;
import com.lyz.models.UserVO;
import com.lyz.utils.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    private final UserController userController;

    public AuthInterceptor(UserController userController) {
        this.userController = userController;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod api = (HandlerMethod) handler;
        if (api.hasMethodAnnotation(Auth.class)) {
            Auth methodAnnotation = api.getMethodAnnotation(Auth.class);
            String value = methodAnnotation.value();
            String token = request.getHeader(TokenUtil.TOKEN_HEADER);
            if (Objects.isNull(userController.tokenMap.get(token))) {
                throw new RuntimeException("UnAuthorization");
            }
            if (TokenUtil.expired(token)) {
                throw new RuntimeException("Authorization Expired");
            }
            UserVO userVO = TokenUtil.parse(token, UserVO.class);
            String permission = userVO.getPermission();
            return value.equals(permission);
        }
        return true;
    }
}
